<?php
use think\Db;
// 应用公共文件
/**
 * 系统非常规MD5加密方法
 * @param  string $str 要加密的字符串
 * @return string
 */
function hb_member_md5($str, $key = 'HuiboMember20180310'){
	return '' === $str ? '' : md5(sha1($str) . $key);
}
/**
 * 时间戳格式化
 * @param int $time
 * @return string 完整的时间显示
 * @author wapai   邮箱:zipzty@gmail.com
 */
function time_format($time = NULL,$format='Y-m-d H:i'){
	$time = $time === NULL ? time() : intval($time);
	return date($format, $time);
}
function time_nianyueri($time = NULL,$format='Y-m-d'){
	$time = $time === NULL ? time() : intval($time);
	return date($format, $time);
}
function time_yueri($time = NULL,$format='m-d'){
	$time = $time === NULL ? time() : intval($time);
	return date($format, $time);
}
function time_nianyue($time = NULL,$format='Y-m'){
	$time = $time === NULL ? time() : intval($time);
	return date($format, $time);
}
function time_nian($time = NULL,$format='Y'){
	$time = $time === NULL ? time() : intval($time);
	return date($format, $time);
}
function time_yue($time = NULL,$format='m'){
	$time = $time === NULL ? time() : intval($time);
	return date($format, $time);
}

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
 */
function get_client_ip($type = 0, $adv = false) {
	$type      = $type ? 1 : 0;
	static $ip = NULL;
	if ($ip !== NULL) {
		return $ip[$type];
	}

	if ($adv) {
		if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
			$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
			$pos = array_search('unknown', $arr);
			if (false !== $pos) {
				unset($arr[$pos]);
			}

			$ip = trim($arr[0]);
		} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
			$ip = $_SERVER['HTTP_CLIENT_IP'];
		} elseif (isset($_SERVER['REMOTE_ADDR'])) {
			$ip = $_SERVER['REMOTE_ADDR'];
		}
	} elseif (isset($_SERVER['REMOTE_ADDR'])) {
		$ip = $_SERVER['REMOTE_ADDR'];
	}
	// IP地址合法验证
	$long = sprintf("%u", ip2long($ip));
	$ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
	return $ip[$type];
}
/*
 * 获取村镇信息 主要是一级分类
 * id
 */

function get_towns($code){
  if($code){
  	$info=Db::name('Towns')->where('code',$code)->value('tname');
  	if($info){
  		return $info;
	}else{
  		return 'error';
	}
  }else{
  	return 'canshuerror';
  }
}
/*
 * 获取村镇信息 主要是一级分类及其下属分类
 * pid
 */
function get_alltowns($code){
	if($code){
		$info=Db::name('Towns')->where('code',$code)->find();
		if($info){
			$infos=Db::name('Towns')->where('code',$info['pid'])->value('tname');
			return $infos.'-'.$info['tname'];
		}else{
			return 'error';
		}
	}else{
		return 'canshuerror';
	}
}
/*
 * 获取单位信息
 * id 单位
 */

function get_danwei($id){
 if($id){
	 $info=Db::name('Danwei')->where('id',$id)->value('bname');
	 if($info){
		 return $info;
	 }else{
		 return 'error';
	 }
 }else{
	 return 'canshuerror';
 }
}
/*
 * 获取单位信息
 * id 单位
 */
function get_department($id){
 if($id){
	 $info=Db::name('department')->where('id',$id)->value('name');
	 if($info){
		 return $info;
	 }else{
		 return 'error';
	 }
 }else{
	 return 'canshuerror';
 }
}
/*
 * 获取分类信息
 * id 分类
 */
function get_catname($id){
	if($id){
		$info=Db::name('Cat')->where('id',$id)->value('title');
		if($info){
			return $info;
		}else{
			return 'error';
		}
	}else{
		return 'canshuerror';
	}
}

/**
 * Excel转换时间
 * @param $date
 * @param bool|false $time
 * @return array|int|string
 */
function excelTime($date, $time = false) {
	if (function_exists('GregorianToJD')) {
		if (is_numeric($date)) {
			$jd = GregorianToJD(1, 1, 1970);
			$gregorian = JDToGregorian($jd + intval($date) - 25569);
			$date = explode('/', $gregorian);
			$date_str = str_pad($date[2], 4, '0', STR_PAD_LEFT) . "-" . str_pad($date[0], 2, '0', STR_PAD_LEFT) . "-" . str_pad($date[1], 2, '0', STR_PAD_LEFT) . ($time ? " 00:00:00" : '');
			return $date_str;
		}
	} else {
		$date = $date > 25568 ? $date + 1 : 25569; /*There was a bug if Converting date before 1-1-1970 (tstamp 0)*/
		$ofs = (70 * 365 + 17 + 2) * 86400;
		$date = date("Y-m-d", ($date * 86400) - $ofs) . ($time ? " 00:00:00" : '');
	}
	return $date;
}
/**
 *  根据身份证号码获取性别
 *  author:xiaochuan
 *  @param string $idcard    身份证号码
 *  @return int $sex 性别 1男 2女 0未知
 */
function get_sex($idcard) {
	if(empty($idcard)) return null;
	$sexint = (int) substr($idcard, 16, 1);
	return $sexint % 2 === 0 ? '女' : '男';
}

/**
 *  根据身份证号码获取生日
 *  author:xiaochuan
 *  @param string $idcard    身份证号码
 *  @return $birthday
 */
function get_birthday($idcard) {
	if(empty($idcard)) return null;
	$bir = substr($idcard, 6, 8);
	$year = (int) substr($bir, 0, 4);
	$month = (int) substr($bir, 4, 2);
	$day = (int) substr($bir, 6, 2);
	return $year . "-" . $month . "-" . $day;
}

/**
 *  根据身份证号码计算年龄
 *  author:xiaochuan
 *  @param string $idcard    身份证号码
 *  @return int $age
 */
function get_age($idcard){
	if(empty($idcard)) return null;
	#  获得出生年月日的时间戳
	$date = strtotime(substr($idcard,6,8));
	#  获得今日的时间戳
	$today = strtotime('today');
	#  得到两个日期相差的大体年数
	$diff = floor(($today-$date)/86400/365);
	#  strtotime加上这个年数后得到那日的时间戳后与今日的时间戳相比
	$age = strtotime(substr($idcard,6,8).' +'.$diff.'years')>$today?($diff+1):$diff;
	return $age;
}

/**
 * 获取一张图片
 * @param $content
 * @param string $order
 * @return string
 */
function get_one_image($content,$order='ALL'){
	$pattern="/<img.*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";
	preg_match_all($pattern,$content,$match);
	if(isset($match[1])&&!empty($match[1])){
		if($order==='ALL'){
			return $match[1][0];
		}
		if(is_numeric($order)&&isset($match[1][$order])){
			return $match[1][$order];
		}
	}
	return '';
}

/**
 *
 * @param $array
 * @param $field
 * @param string $sort
 * @return mixed
 */
function arraySequence($array, $field, $sort = 'SORT_DESC')
{
	$arrSort = array();
	foreach ($array as $uniqid => $row) {
		foreach ($row as $key => $value) {
			$arrSort[$key][$uniqid] = $value;
		}
	}
	array_multisort($arrSort[$field], constant($sort), $array);
	return $array;
}

/**
 * 对象转数组
 * @param $array
 * @return array
 */
function object_array($array) {
	if(is_object($array)) {
		$array = (array)$array;
	} if(is_array($array)) {
		foreach($array as $key=>$value) {
			$array[$key] = object_array($value);
		}
	}
	return $array;
}

/**
 * 获取文件路径
 * @param $dizhi
 * @return string
 */
function wenjianpath($dizhi){
   return 'http://'.$_SERVER['HTTP_HOST'].'/newsfusheng/'.$dizhi;
}

/**
 * 获取
 * @param $ids
 * @return string
 */
function get_aidtitle($ids){
   switch ($ids){
	   case '1':
	   	return '资金类';
	   	break;
	   case '2':
		   return '负债类';
		   break;
	   case '3':
		   return '所有者权益';
		   break;
	   case '4':
		   return '成本类';
		   break;
	   case '5':
		   return '损益类';
		   break;
	   default:
		   return '资金类';
   }
}

/**
 * 获取月份信息
 * @param $shuzhi
 * @return string\
 */
function get_yuefenwenzi($shuzhi)
{
	switch ($shuzhi) {
		case '1':
			return '一月';
			break;
		case '2':
			return '二月';
			break;
		case '3':
			return '三月';
			break;
		case '4':
			return '四月';
			break;
		case '5':
			return '五月';
			break;
		case '6':
			return '六月';
			break;
		case '7':
			return '七月';
			break;
		case '8':
			return '八月';
			break;
		case '9':
			return '九月';
			break;
		case '10':
			return '十月';
			break;
		case '11':
			return '十一月';
			break;
		case '12':
			return '十二月';
			break;
		default:
			return '一月';
	   }
	}
function get_oyuefenwenzi($shuzhi)
	{
		switch ($shuzhi) {
			case '1':
				return '01月';
				break;
			case '2':
				return '02月';
				break;
			case '3':
				return '03月';
				break;
			case '4':
				return '04月';
				break;
			case '5':
				return '05月';
				break;
			case '6':
				return '06月';
				break;
			case '7':
				return '07月';
				break;
			case '8':
				return '08月';
				break;
			case '9':
				return '09月';
				break;
			case '10':
				return '10月';
				break;
			case '11':
				return '11月';
				break;
			case '12':
				return '12月';
				break;
			default:
				return '01月';
		}
	}

//记录操作日志
	function get_log($uid, $title, $mark = '')
	{
		if ($uid > 0) {
			$datas['uid'] = $uid;
			$datas['title'] = $title;
			$datas['mark'] = $mark;
			$datas['create_time'] = time();
			$idss = \think\Db::name('Caozuolog')->insert($datas);

		}
	}

/**
 *
 * @param $number
 * @return array|string
 */
	function get_chaifengjiage($number)
	{
		if ($number > 0) {
			$shuzi = $number * 100;
			$sz = str_split($shuzi);

			$zsz = array_reverse(array_merge(['￥'], $sz));

			return $zsz;
		} else {
			return '';
		}
	}

	//通过科目编号来获取科目属性
	function get_numberaid($number = 0)
	{
		$xx = \think\Db::name('Subject')->where('number', $number)->value('aid');
		return get_subjectattr($xx);
	}

	//获取资金属性
	function get_subjectattr($id)
	{
		switch ($id) {
			case '1':
				return '资金类';
				break;
			case '2':
				return '负债类';
				break;
			case '3':
				return '所有者权益';
				break;
			case '4':
				return '成本类';
				break;
			case '5':
				return '损益类';
				break;

			default:
				return '资金类';
				break;
		}
	}

/**
 * 获取用户昵称
 * @param $uid
 * @return mixed|string
 */
	function get_nickname($uid){
        if($uid){
           return  $info=\think\Db::name('Member')->where('id',$uid)->value('nickname');
		}else{
        	return '无用户id';
		}
	}
//获取科目月结数据
//参数 ：townsid  year month sbiaohao
//村镇id  年份  月份  科目编号

function get_monthsubject($townsid,$year,$month,$bianhao,$times){
	if($townsid&&$year&&$month&&$bianhao){
		$maps[]=array('townsid','=',$townsid);
		$maps[]=array('year','=',$year);
		$maps[]=array('month','=',$month);
		$maps[]=array('sbianhao','=',$bianhao);
		$czinfo=\think\Db::name('Sbalance')->where($maps)->field('id,sbianhao,initbalance,endbalance,month,year,debit,credit')->find();

		$zids=0;
		if($czinfo){
			return $czinfo;
		}else{
			if($month==1){
				$smonth=12;
				$syear=$year-1;
			}else{
				$smonth=$month-1;
				$syear=$year;
			}

			$smaps[]=array('townsid','=',$townsid);
			$smaps[]=array('year','=',$syear);
			$smaps[]=array('month','=',$smonth);
			$smaps[]=array('sbianhao','=',$bianhao);
			$sczinfo=\think\Db::name('Sbalance')->where($smaps)->field('id,sbianhao,initbalance,endbalance,month,year,debit,credit,sname')->find();

			if(!$sczinfo){
				//获取初始化数据

				$mapinit[]=array('townsid','=',$townsid);
				$mapinit[]=array('sbianhao','=',$bianhao);

				$initinfo=\think\Db::name('Subjectinfo')->where($mapinit)->find();

                unset($mapinit);
				if($initinfo){
					$xinze['sbianhao']=$initinfo['sbianhao'];
					$xinze['sname']=$initinfo['sname'];
					$xinze['initbalance']=$initinfo['initbalance'];
					$xinze['endbalance']=$initinfo['endbalance'];
					$xinze['year']=$year;
					$xinze['month']=$month;
					$xinze['townsid']=$townsid;
					$xinze['debit']=0;
					$xinze['credit']=0;
					$xinze['create_time']=$times;

					$zids=\think\Db::name('Sbalance')->insertGetId($xinze);
					unset($initinfo);
				}
			}else{

				$xinze['sbianhao']=$sczinfo['sbianhao'];
				$xinze['sname']=$sczinfo['sname'];
				$xinze['initbalance']=$sczinfo['endbalance'];
				$xinze['endbalance']=0;
				$xinze['year']=$year;
				$xinze['month']=$month;
				$xinze['townsid']=$townsid;
				$xinze['debit']=0;
				$xinze['credit']=0;
				$xinze['create_time']=$times;
				$zids=\think\Db::name('Sbalance')->insertGetId($xinze);

			}


			if($zids>0){
				$sczinfos=\think\Db::name('Sbalance')->where('id',$zids)->field('id,sbianhao,initbalance,endbalance,month,year,debit,credit')->find();

				return $sczinfos;
			}else{
				return '';
			}
		}
	}else{
		return '';
	}
}

/**
 * @param $nums
 * @return float
 */
function get_shuliang($nums){
	return ceil($nums/5);
}
/**
 * 通过zjmgid来获取到zijinmenage的资金名称
 * 2014.04.08
 */
function get_zijinmingcheng($key){
	if($key){
		$zijininfo=\think\Db::name('Zijinmanage')->where('id',$key)->value('title');
		return $zijininfo;
	}

}
/**
 *通过catid来获取到资金分类名称
 *2014.03.22
 */
function get_zjcat($id){
	$info=\think\Db::name('Zijincat')->where('id',$id)->value('title');
	return $info;

}

//获取政策原文标题 20160229
function get_zcyw($id){
	if($id){
		$info=\think\Db::name('Huimin')->where('id',$id)->value('title');
		if($info){
			return $info;
		}
	}
}
//冒泡事件排序 从小到大排序
function bubbleSort($arr)
{
	$length = count($arr);
	for ($i=1; $i < $length; $i++) {
		for ($k=0; $k < $length-$i; $k++) {
			if ($arr[$k]>$arr[$k+1]) {
//				=为赋值  //相邻比较
					$tem=$arr[$i];
//				=为赋值  $arr[$i+1]=$arr[$i]+1
					$arr[$i]=$arr[$i+1];
					$arr[$i+1]=$tem;
			}
		}
	}
	return $arr;
}



if(!function_exists('p')) {
	function p($data, $flag = 0, $break = 1)
	{
		echo '<pre>';
		if (!empty($flag))
			var_dump($data);
		else
			print_r($data);
		echo '</pre>';
		if (!empty($break))
			exit();
	}
}
//日志
function loggers($content){

	$max_size = 10000;
	$log_filename = "../log.xml";
	if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
	if(is_array($content)){
		file_put_contents($log_filename, date('H:i:s')." ".json_encode($content)."\r\n", FILE_APPEND);
	}else{
		file_put_contents($log_filename, date('H:i:s')." ".$content."\r\n", FILE_APPEND);
	}

}
//获取用户权限组。1.超级管理员。2.区级 3 镇级。4.村级
function get_usergroup($uid){
	if($uid>=1){
		if($uid==1){
			return 1;
		}else{
			$zb=\think\Db::name('Auth_group_access')->where('uid',$uid)->value('group_id');
			if($zb){
				return $zb;
			}else{
				return 0;
			}
		}
	}else{
		return 0;
	}
}

//将科学计数法转换为原始数字字符串的方法
function NumToStr($num){
	if (stripos($num,'e')===false) return $num;
	$num = trim(preg_replace('/[=\'"]/','',$num,1),'"');//出现科学计数法，还原成字符串
	$result = "";
	while ($num > 0){
		$v = $num - floor($num / 10)*10;
		$num = floor($num / 10);
		$result = $v . $result;
	}
	return $result;
}

/**
 * 获取权限
 * @param $kongzhi
 * @param $uid
 * @param $group_id
 * @return int
 */
function get_apiquanxian($kongzhi,$uid,$group_id){
//	echo $kongzhi,$uid,$group_id;exit;
	if($kongzhi && $uid && $group_id){
		//从权限组表中得到规则
		$rules=Db::name('Auth_group')->where('id',$group_id)->value('rules');

		if($rules){
			$rules=explode(',',$rules);

			$ids=Db::name('Menu')->where('api',$kongzhi)->value('id');

			if($ids){

				if(in_array($ids,$rules)){
					return 1;
				}else{
					return 0;
				}
			}else{
				return 0;
			}
		}else{
			return 0;
		}
	}else{
		return 0;
	}

}


function alpha2num($a) {
	$l = strlen($a);
	$n = 0;
	for($i = 0; $i < $l; $i++)
		$n = $n*26 + ord($a[$i]) - 0x40;

	return $n-1;
}

// to convert number back to alpha
function num2alpha($n)
{
	for($r = ""; $n >= 0; $n = intval($n / 26) - 1)
		$r = chr($n%26 + 0x41) . $r;
	return $r;
}

function get_range($start_column, $end_column)
{
	$s = alpha2num($start_column); // get start number
	$e = alpha2num($end_column); // get end num

	$columns = [];

	// loop from start to end and change back the number to alpha to be stored in array
	for ($i = $s; $i <= $e; $i++) {
		$columns[] = num2alpha($i);
	}

	return $columns;
}
function get_luyous($array,$pid){

	$temp = array();
	foreach ($array as $v) {
		if ($v['pid'] == $pid) {
			$v['children'] = get_luyous($array,$v['id']);
			$result = count($v['children']);
			if($result < 1){
				unset($v['children']);
			}
			$temp[] = $v;
		}
	}
	return $temp;


}
function get_luyousdz($array,$pid){

	$temp = array();
	foreach ($array as $v) {
		if($pid==0){
			$temp[]=$v;
		}else{
			if ($v['pid'] == $pid) {
				$v['children'] = get_luyous($array,$v['id']);
				$result = count($v['children']);
				if($result < 1){
					unset($v['children']);
				}
				$temp[] = $v;
			}
		}
	}
	return $temp;


}

function get_authcaidanlist($uid){
	$group_id=Db::name('Auth_group_access')->where('uid',$uid)->value('group_id');
	$rules=Db::name('Auth_group')->where('id',$group_id)->value('rules');
	if($rules){
		$rules=explode(',',$rules);
		$cdinfo=Db::name('Menu')->order('sort ASC')->select();
		if($cdinfo){
			foreach ($cdinfo as $key=>$value){
				if(in_array($value['id'],$rules)){
					$cdinfo[$key]['access']=1;
					$cdinfo[$key]['checked']=true;
				}else{
					$cdinfo[$key]['access']=2;
					$cdinfo[$key]['checked']=false;
				}
			}

			return get_luyous($cdinfo, 0);
		}
	}
}
function get_authanniulist($uid){
	$group_id=Db::name('Auth_group_access')->where('uid',$uid)->value('group_id');
	$rules=Db::name('Auth_group')->where('id',$group_id)->value('rules');
	if($rules){
		$rules=explode(',',$rules);
		$cdinfo=Db::name('Menu')->where('type','2')->order('sort ASC')->select();
		if($cdinfo){
			foreach ($cdinfo as $key=>$value){
				if(in_array($value['id'],$rules)){
					$cdinfo[$key]['access']=1;
					$cdinfo[$key]['checked']=true;
				}else{
					$cdinfo[$key]['access']=2;
					$cdinfo[$key]['checked']=false;
				}
			}

			return get_luyous($cdinfo, 0);
		}
	}
}
function get_authotherlist($uid){
	$group_id=Db::name('Auth_group_access')->where('uid',$uid)->value('group_id');
	$rules=Db::name('Auth_group')->where('id',$group_id)->value('rules');
	if($rules){
		$rules=explode(',',$rules);
		$cdinfo=Db::name('Menu')->where('type','3')->order('sort ASC')->select();

		if($cdinfo){
			foreach ($cdinfo as $key=>$value){
				if(in_array($value['id'],$rules)){
					$cdinfo[$key]['access']=1;
					$cdinfo[$key]['checked']=false;
				}else{
					$cdinfo[$key]['access']=2;
					$cdinfo[$key]['checked']=false;
				}
			}

			return get_luyousdz($cdinfo,0);
		}
	}
}

